﻿using Microsoft.AspNetCore.Identity;
using PYNET.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Newtonsoft.Json;
using PYNET.Utils;
using Microsoft.AspNetCore.StaticFiles;
using PYNET.Data;

namespace PYNET.Controllers
{
    public class ArticlesController : Controller
    {
        private readonly ArticleSystemDbContext _context;
        private readonly SignInManager<User> _signInManager;
        private readonly UserManager<User> _userManager;
        private readonly RoleManager<TIdentityRole> _roleManager;
        private readonly IWebHostEnvironment _env;
        public ArticlesController(
            SignInManager<User> signInManager,
            UserManager<User> userManager,
            RoleManager<TIdentityRole> roleManager,
            ArticleSystemDbContext context,
            IWebHostEnvironment env)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _roleManager = roleManager;
            _context = context;
            _env = env;
        }

        public async Task<IActionResult> ArticleIndex()
        {
            var Articles = await _context.Articles.ToListAsync();
            List<ArticleIndexViewModel> articleIndexViewModels = new List<ArticleIndexViewModel>();
            foreach (var article in Articles)
            {
                var name = await _userManager.FindByIdAsync(article.UId.ToString());
                if (name != null)
                {
                    articleIndexViewModels.Add(new ArticleIndexViewModel
                    {
                        AId = article.AId,
                        UserName = name.UserName,
                        Title = article.Title,
                        Content = article.Content,
                        LikeNumber = article.LikeNumber,
                        Introduce = article.Introduce,
                        ArticlePicture=article.ArticlePicture
                    });
                }
                else
                {
                    articleIndexViewModels.Add(new ArticleIndexViewModel
                    {
                        AId = article.AId,
                        UserName = "已注销用户",
                        Title = article.Title,
                        Content = article.Content,
                        LikeNumber = article.LikeNumber,
                        Introduce = article.Introduce,
                        ArticlePicture = article.ArticlePicture
                    });
                }
            }
            return View(articleIndexViewModels);
        }

        public async Task<IActionResult> ArticleDetail(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var article = await _context.Articles.FindAsync(id);
            if (article == null)
            {
                return NotFound();
            }
            var name = await _userManager.FindByIdAsync(article.UId.ToString());
            if (name == null)
            {
                name = new User
                {
                    Id = article.UId,
                    UserName = "用户已注销",
                    HeadPicture = "Default.jpg"
                };
            }
            //var comments = from s in _context.Comments
            //               select s;
            //comments = comments.Where(s => s.AId.Equals(id)||s.Type.Equals(1));
            var comments = await _context.Comments.Where(s => s.AId.Equals(id) && s.Type.Equals(0)).ToListAsync();
            List<ArticleComments> articleComments = new List<ArticleComments>();
            foreach (var comment in comments)
            {
                //var subcomments= from s in _context.Comments
                //                 select s;
                //subcomments = subcomments.Where(s => s.TargetId.Equals(comment.CId));
                var subcomments = await _context.Comments.Where(s => s.TargetId.Equals(comment.CId)).ToListAsync();
                foreach (var subcomment in subcomments)
                {
                    var _userCommentLikes = _context.UserCommentLikes.Where(t => t.Cid.Equals(subcomment.CId) && t.Uid.Equals(name.Id)).Count() > 0;
                    if (_userCommentLikes)
                    {
                        subcomment.Liked = 1;
                    }
                    else
                    {
                        subcomment.Liked = 0;
                    }
                }
                bool userCommentLikes;
                if (_signInManager.IsSignedIn(User)) { 
                    userCommentLikes = _context.UserCommentLikes.Where(t => t.Cid.Equals(comment.CId) && t.Uid.Equals(name.Id)).Count() > 0;
                }
                else
                {
                    userCommentLikes = false;
                }
                if (userCommentLikes)
                {
                    comment.Liked = 1;
                }
                else
                {
                    comment.Liked = 0;
                }
                articleComments.Add(new ArticleComments
                {
                    comment = comment,
                    subcomments = subcomments
                });
            }
            bool isLiked;
            if (_signInManager.IsSignedIn(User))
            {
                isLiked = _context.UserArticleLikes.Where(t => t.Aid.Equals(article.AId) && t.Uid.Equals(name.Id)).Count() > 0;
            }
            else
            {
                isLiked = false;
            }
            ArticleWithComments articleWithComments = new ArticleWithComments
            {
                article = article,
                articleComments = articleComments,
                UserName = name.UserName,
                Liked = isLiked ? 1 : 0
            };
            return View(articleWithComments);
        }

        [Authorize]
        [HttpPost]
        public async Task<IActionResult> ArticleLike()
        {
            var id = Request.Form["Aid"];
            var article = await _context.Articles.FindAsync(Convert.ToInt32(id));
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (article == null)
            {
                return new JsonResult("无此评论！");
            }
            article.LikeNumber = article.LikeNumber + 1;
            UserArticleLike userArticleLike = new UserArticleLike
            {
                Uid = user.Id,
                Aid = article.AId
            };
            _context.Articles.Update(article);
            _context.UserArticleLikes.Update(userArticleLike);
            await _context.SaveChangesAsync();
            return new JsonResult("Success");
        }

        [Authorize]
        [HttpPost]
        public async Task<IActionResult> CommentLike()
        {
            var id = Request.Form["Cid"];
            var comment = await _context.Comments.FindAsync(Convert.ToInt32(id));
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (comment == null)
            {
                return new JsonResult("无此评论！");
            }
            comment.LikeNumber = comment.LikeNumber + 1;
            UserCommentLike userCommentLike = new UserCommentLike
            {
                Uid = user.Id,
                Cid = comment.CId
            };
            _context.Comments.Update(comment);
            _context.UserCommentLikes.Update(userCommentLike);
            await _context.SaveChangesAsync();
            return new JsonResult("Success");
        }



        [Authorize]
        [HttpPost]
        public async Task<IActionResult> Comment()
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            Comment comment = new Comment
            {
                AId = Convert.ToInt32(Request.Form["AId"]),
                Type = Convert.ToInt32(Request.Form["Type"]),
                TargetId = Convert.ToInt32(Request.Form["TargetId"]),
                TargetName = Request.Form["TargetName"],
                UName = user.UserName,
                Content = Request.Form["Content"],
                UId = user.Id,
                LikeNumber = 0,
                Liked = 0
            };
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(comment);
                    await _context.SaveChangesAsync();
                    return new JsonResult("成功！");
                }
                else
                {
                    return new JsonResult("模型错误！");
                }
            }
            catch
            {
                return new JsonResult("失败！");
            }
        }

        [HttpPost]
        public async Task<IActionResult> ArticleSearch(string searchString)
        {
            var articles = from s in _context.Articles
                           select s;
            var article2 = new List<Article>();
            if (searchString!=null)
            {
                articles = articles.Where(s => s.Title.Contains(searchString));
            }
            else
            {
                return View(article2);
            }
            return View(await articles.ToListAsync());
        }
    }
}
